package com.meiyuetao.myt.job;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

import lab.s2jh.ctx.MailService;
import lab.s2jh.schedule.BaseQuartzJobBean;

import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

/**
 * 2015/6/25 执行一次，签到功能关闭，邮件短信通知，改功能废弃
 * 
 * @author harvey
 * 
 */
public class CloseCheckIn extends BaseQuartzJobBean {

    @Override
    protected void executeInternalBiz(JobExecutionContext context) {
        MailService mailService = this.getSpringBean(MailService.class);
        BusinessNotifyService businessNotifyService = this.getSpringBean(BusinessNotifyService.class);
        JdbcTemplate jdbcTemplate = this.getSpringBean(JdbcTemplate.class);
        String sql = "SELECT email, mobile_phone FROM iyb_customer_profile WHERE sid IN " + "(SELECT DISTINCT customer_profile_sid FROM iyb_customer_account_history )"
                + "AND email != '' AND mobile_phone !=''";
        final List<String[]> list = new ArrayList<String[]>();
        jdbcTemplate.query(sql, new RowCallbackHandler() {

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                String[] str = new String[2];
                str[0] = rs.getString("email");
                str[1] = rs.getString("mobile_phone");
                list.add(str);
            }
        });

        for (String[] str : list) {
            String email = str[0].trim();
            String mobilePhone = str[1].trim();
            String content = "美月淘用户您好，签到功能将于2015年6月29号19点关闭使用，凡是在2015年6月29日19点之前签到的用户，我们会将签到金转入您的美月淘账号，需要提现的用户请联系美月淘客服 400-898-6221。";
            try {
                if (isEmail(email)) {
                    mailService.sendHtmlMail("公告", content, false, email);
                }
                if (!StringUtils.isEmpty(mobilePhone)) {
                    businessNotifyService.sendSmsByYunPian(mobilePhone, "855843", "#year#=2015");
                }
            } catch (Exception e) {
                continue;
            }
        }
    }

    public boolean isEmail(String value) {
        if (value == null || value.length() == 0) {
            return false;
        }
        java.util.regex.Pattern p = null;
        Matcher m = null;
        p = java.util.regex.Pattern
                .compile("\\b(^['_A-Za-z0-9-]+(\\.['_A-Za-z0-9-]+)*@([A-Za-z0-9-])+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z0-9]{2,})|(\\.[A-Za-z0-9]{2,}\\.[A-Za-z0-9]{2,}))$)\\b");
        m = p.matcher(value);
        return m.find();
    }
}
